package com.taxx.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.taxx.excel.IncomeExcelData;
import com.taxx.excel.IdentityExcelData;
import com.taxx.excel.PlatformExcelData;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * Excel模板下载控制器
 * 
 * @author taxx
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/excel/template")
@CrossOrigin
public class ExcelTemplateController {

    /**
     * 下载收入信息Excel模板
     */
    @GetMapping("/income")
    public void downloadIncomeTemplate(HttpServletResponse response) throws IOException {
        try {
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("收入信息导入模板.xlsx", StandardCharsets.UTF_8.toString());
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);

            // 创建示例数据
            List<IncomeExcelData> dataList = createIncomeSampleData();

            // 设置样式
            WriteCellStyle headStyle = createHeadStyle();
            WriteCellStyle contentStyle = createContentStyle();
            HorizontalCellStyleStrategy styleStrategy = new HorizontalCellStyleStrategy(headStyle, contentStyle);

            // 写入Excel
            EasyExcel.write(response.getOutputStream(), IncomeExcelData.class)
                .registerWriteHandler(styleStrategy)
                .sheet("收入信息")
                .doWrite(dataList);

            log.info("收入信息Excel模板下载成功");
        } catch (Exception e) {
            log.error("收入信息Excel模板下载失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 下载身份信息Excel模板
     */
    @GetMapping("/identity")
    public void downloadIdentityTemplate(HttpServletResponse response) throws IOException {
        try {
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("身份信息导入模板.xlsx", StandardCharsets.UTF_8.toString());
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);

            // 创建示例数据
            List<IdentityExcelData> dataList = createIdentitySampleData();

            // 设置样式
            WriteCellStyle headStyle = createHeadStyle();
            WriteCellStyle contentStyle = createContentStyle();
            HorizontalCellStyleStrategy styleStrategy = new HorizontalCellStyleStrategy(headStyle, contentStyle);

            // 写入Excel
            EasyExcel.write(response.getOutputStream(), IdentityExcelData.class)
                .registerWriteHandler(styleStrategy)
                .sheet("身份信息")
                .doWrite(dataList);

            log.info("身份信息Excel模板下载成功");
        } catch (Exception e) {
            log.error("身份信息Excel模板下载失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 下载平台信息Excel模板
     */
    @GetMapping("/platform")
    public void downloadPlatformTemplate(HttpServletResponse response) throws IOException {
        try {
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("平台信息导入模板.xlsx", StandardCharsets.UTF_8.toString());
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);

            // 创建示例数据
            List<PlatformExcelData> dataList = createPlatformSampleData();

            // 设置样式
            WriteCellStyle headStyle = createHeadStyle();
            WriteCellStyle contentStyle = createContentStyle();
            HorizontalCellStyleStrategy styleStrategy = new HorizontalCellStyleStrategy(headStyle, contentStyle);

            // 写入Excel
            EasyExcel.write(response.getOutputStream(), PlatformExcelData.class)
                .registerWriteHandler(styleStrategy)
                .sheet("平台信息")
                .doWrite(dataList);

            log.info("平台信息Excel模板下载成功");
        } catch (Exception e) {
            log.error("平台信息Excel模板下载失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 创建收入信息示例数据
     */
    private List<IncomeExcelData> createIncomeSampleData() {
        List<IncomeExcelData> dataList = new ArrayList<>();
        
        // 动态计算当前时间和上一季度
        LocalDate now = LocalDate.now();
        int currentYear = now.getYear();
        int currentMonth = now.getMonthValue();
        
        // 计算上一季度
        int lastQuarter = (currentMonth - 1) / 3 + 1;
        int lastQuarterYear = currentYear;
        if (lastQuarter == 1) {
            lastQuarter = 4;
            lastQuarterYear = currentYear - 1;
        } else {
            lastQuarter = lastQuarter - 1;
        }
        
        // 计算上一季度的起止时间
        int startMonth = (lastQuarter - 1) * 3 + 1;
        int endMonth = lastQuarter * 3;
        
        LocalDate startDate = LocalDate.of(lastQuarterYear, startMonth, 1);
        LocalDate endDate = LocalDate.of(lastQuarterYear, endMonth, endMonth == 2 ? 28 : 
                                       (endMonth == 4 || endMonth == 6 || endMonth == 9 || endMonth == 11) ? 30 : 31);
        
        // 添加示例行
        IncomeExcelData sample1 = new IncomeExcelData();
        sample1.setStartTime(startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        sample1.setEndTime(endDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        sample1.setHasRegistration("1");
        sample1.setCreditCode("91110000123456789X");
        sample1.setTaxpayerName("示例纳税人");
        sample1.setMerchantId("MER001");
        sample1.setMerchantName("示例商户");
        sample1.setGoodsIncome("10000.00");
        sample1.setGoodsRefund("0.00");
        sample1.setIntangibleIncome("5000.00");
        sample1.setIntangibleRefund("0.00");
        sample1.setServiceIncome("8000.00");
        sample1.setServiceRefund("0.00");
        sample1.setUnregisteredIncome("3000.00");
        sample1.setUnregisteredRefund("0.00");
        sample1.setNetIncomeGoods("2000.00");
        sample1.setNetIncomeTransport("1000.00");
        sample1.setNetIncomeLabor("1500.00");
        sample1.setNetIncomeRoyalty("500.00");
        sample1.setNetIncomeFranchise("800.00");
        sample1.setOtherNetIncome("1200.00");
        sample1.setPlatformCommission("500.00");
        sample1.setTransactionCount("100");
        dataList.add(sample1);
        
        return dataList;
    }

    /**
     * 创建身份信息示例数据
     */
    private List<IdentityExcelData> createIdentitySampleData() {
        List<IdentityExcelData> dataList = new ArrayList<>();
        
        // 添加示例行
        IdentityExcelData sample1 = new IdentityExcelData();
        sample1.setHasRegistration("1");
        sample1.setCreditCode("91110000123456789X");
        sample1.setTaxpayerName("示例纳税人");
        sample1.setDetailedAddress("北京市朝阳区示例街道123号");
        sample1.setMerchantId("MER001");
        sample1.setMerchantName("示例商户");
        sample1.setWebsite("https://example.com");
        sample1.setContactPerson("张三");
        sample1.setContactPhone("13800138000");
        sample1.setBusinessStartTime("2024-01-01");
        sample1.setOperationTypeCode("01");
        sample1.setProfessionalServiceIdentifier("PS001");
        sample1.setSettlementAccountInfo("中国银行 1234567890");
        dataList.add(sample1);
        
        return dataList;
    }

    /**
     * 创建平台信息示例数据
     */
    private List<PlatformExcelData> createPlatformSampleData() {
        List<PlatformExcelData> dataList = new ArrayList<>();
        
        // 添加示例行
        PlatformExcelData sample1 = new PlatformExcelData();
        sample1.setTaxpayerName("示例平台企业");
        sample1.setCreditCode("91110000123456789X");
        sample1.setPlatformName("示例平台");
        sample1.setPlatformId("PLAT001");
        sample1.setBusinessStartTime("2024-01-01");
        sample1.setBusinessExitTime(null);
        sample1.setOperationTypeCode("01");
        dataList.add(sample1);
        
        return dataList;
    }

    /**
     * 创建表头样式
     */
    private WriteCellStyle createHeadStyle() {
        WriteCellStyle headStyle = new WriteCellStyle();
        // 设置背景色
        headStyle.setFillForegroundColor((short) 22);
        headStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        // 设置字体
        WriteFont headFont = new WriteFont();
        headFont.setFontHeightInPoints((short) 12);
        headFont.setBold(true);
        headFont.setColor((short) 8);
        headStyle.setWriteFont(headFont);
        return headStyle;
    }

    /**
     * 创建内容样式
     */
    private WriteCellStyle createContentStyle() {
        WriteCellStyle contentStyle = new WriteCellStyle();
        // 设置字体
        WriteFont contentFont = new WriteFont();
        contentFont.setFontHeightInPoints((short) 11);
        contentStyle.setWriteFont(contentFont);
        return contentStyle;
    }
}
